import { Component, OnInit, ElementRef } from '@angular/core';
import { FormControl, Validators, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-demo6',
  templateUrl: './demo6.component.html'
})
export class Demo6Component implements OnInit {
  name;

  visible: boolean = false;

  errorTips;

  errorTipsMap = {
    required: 'Name cannot be empty.',
    maxlength: 'Length cannot exceed 5.'
  };

  constructor(private fb: FormBuilder, private elementRef: ElementRef) {}

  ngOnInit() {
    this.initForm();

    this.checkInvalid(this.name);
    this.name.statusChanges.subscribe(() => {
      this.checkInvalid(this.name);
    });
  }

  initForm() {
    this.name = new FormControl('', [
      Validators.required,
      Validators.maxLength(5)
    ]);
  }

  checkInvalid(control) {
    const invalid = control.invalid && (control.dirty || control.touched);
    this.visible = invalid;

    if (control.errors) {
      this.errorTips = this.errorTipsMap[Object.keys(control.errors)[0]];
    }
  }

  focus() {
    this.checkInvalid(this.name);
  }
}
